<?php

namespace App\Service\OpenShop\Feishu;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

class FeishuApiService
{
    public static function accessToken($siteConfig)
    {
        $app_id     = $siteConfig['appId'];
        $app_secret = $siteConfig['appSecret'];
        $cacheKey   = "feishu_access_token" . $siteConfig['platformName'] . ":" . "{$app_id}";
        $body       = Cache::get($cacheKey);
        if (null !== $body) {
            return $body;
        }
        $response = Http::withHeaders([
            'Content-Type' => 'application/json; charset=utf-8',
        ])->post(
            'https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal',
            compact('app_id', 'app_secret')
        );
        $arr      = json_decode($response->body(), true);
        if (JSON_ERROR_NONE !== json_last_error()) {
            return '';
        }
        $body = $arr['app_access_token'];
        Cache::put($cacheKey, $body, max(0, $arr['expire'] - 60));
        Cache::put("feishu_tenant_access_token_{$app_id}", $arr['tenant_access_token'], max(0, $arr['expire'] - 60));
        return $body;
    }

    public static function loginByCode(string $code, $siteConfig)
    {

        return Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
                   ->withToken(static::accessToken($siteConfig))
                   ->post('https://open.feishu.cn/open-apis/mina/v2/tokenLoginValidate', [
                       'grant_type' => 'authorization_code',
                       'code'       => $code,
                   ])->json();
    }

    public static function userInfo(string $openid, string $user_access_token)
    {
        return Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
                   ->withToken($user_access_token)
                   ->get('https://open.feishu.cn/open-apis/contact/v3/users/' . $openid)
                   ->json();
    }

    public static function getDepartmentName($department_ids, $siteConfig)
    {
        if (!count($department_ids)) {
            return '';
        }
        $departmentInfo = Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
                              ->withToken(static::accessToken($siteConfig))
                              ->get('https://open.feishu.cn/open-apis/contact/v3/departments/parent', [
                                  'department_id' => $department_ids[0],
                              ])->json();

        if (!isset($departmentInfo['code']) || !isset($departmentInfo['data']['items'])) {
            return '';
        }

        if ($departmentInfo['code'] != 0) {
            return '';
        }

        $departmentName = '';
        foreach ($departmentInfo['data']['items'] as $item) {
            if ($item['parent_department_id'] == 0) {
                $departmentName = $item['name'];
            }
        }
        return $departmentName;
    }

    public static function getDepartment(?string $departmentId, array $siteConfig)
    {
        if (!mb_strlen($departmentId)) {
            return '';
        }
        return Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
                   ->withToken(self::accessToken($siteConfig))
                   ->get('https://open.feishu.cn/open-apis/contact/v3/departments/' . $departmentId)->json();
    }

    //通过ID获取用户信息
    public static function getUserInfoByFeishuId($feishuId, $siteConfig)
    {
        return Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
                   ->withToken(static::accessToken($siteConfig))
                   ->get('https://open.feishu.cn/open-apis/contact/v3/users/' . $feishuId,
                       ['user_id_type' => 'user_id'])->json();
    }
}
